package com.wm.blog.center.service.impl;


import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wm.blog.center.common.utils.es.MyElasticUtils;
import com.wm.blog.center.common.utils.login.StpAdminUtil;
import com.wm.blog.center.dao.BlogDao;
import com.wm.blog.center.entity.BlogEntity;
import com.wm.blog.center.service.BlogService;
import com.wm.blog.center.vo.ws.BlogVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service("blogService")
@Slf4j
public class BlogServiceImpl extends ServiceImpl<BlogDao, BlogEntity> implements BlogService {


    @Autowired
    MyElasticUtils myElasticUtils;

    @Override
    @Transactional
    @SaCheckLogin(key = StpAdminUtil.KEY)
    public Boolean saveBlog(BlogVo blogVo) {
        try {
            BlogEntity blogEntity = BlogEntity.builder()
                    .title(blogVo.getTitle())
                    .memberId(StpAdminUtil.getLoginIdAsLong())
                    .build();
            this.save(blogEntity);
            blogVo.setId(blogEntity.getId());
            blogVo.getMember().setId(blogEntity.getMemberId());
            blogVo.setCreateTime(DateUtil.formatDateTime(blogEntity.getCreateTime()));
            myElasticUtils.createIndexIfNotExist(blogVo.getClass());
            myElasticUtils.insertDoc(blogVo);

            return true;
        } catch (Exception e) {
            log.error("添加博客异常！blog={}",blogVo, e);
            return false;
        }
    }
}